﻿using System;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using TFSTools.TFSLibrary;

namespace TFSTools.TestManagement.TestCaseReview
{
    /// <summary>
    /// Interaction logic for MainWindow
    /// </summary>
    public partial class MainWindow : Window
    {
        private TFSConnection connection = null;
        private bool isFirstTimeActivated = false;

        public MainWindow()
        {
            this.InitializeComponent();

            ////LoadServerFromSettings();
        }

        private void LoadServerFromSettings()
        {
            try
            {
                var settings = Properties.Settings.Default;

                tbxTFSServerInfo.Text = "Connecting to TFS...";
                this.Refresh();
                Thread.Sleep(500);

                if (!string.IsNullOrEmpty(settings.TfsUri))
                {
                    this.connection = new TFSConnection(new Uri(settings.TfsUri), settings.TestProject);
                }

                this.UpdateServerInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured.  " + ex.Message);
            }
        }

        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.connection = TFSConnection.LoadProjectSelectionFromUser();
                this.UpdateServerInfo();

                if (this.connection != null)
                {
                    var settings = Properties.Settings.Default;
                    settings.TestProject = this.connection.SelectedProject.Name;
                    settings.TfsUri = this.connection.ServerUri;
                    settings.Save();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured.  " + ex.Message);
            }
        }

        private void UpdateServerInfo()
        {
            if (this.connection != null)
            {
                if (this.connection.SelectedProject != null)
                {
                    tbxTFSServerInfo.Text = this.connection.ServerName + ";" + this.connection.SelectedProject.Name;

                    var queries = this.connection.SelectedProject.GetQueryDefinitions();
                    cmbQueryList.Items.Clear();
                    cmbQueryList.Items.Add("Select Query...");
                    foreach (var query in queries)
                    {
                        cmbQueryList.Items.Add(query);
                    }

                    var settings = Properties.Settings.Default;
                    var selectedQuery = queries.FirstOrDefault(x => x.Path == settings.QueryName);

                    if (selectedQuery != null && cmbQueryList.Items.Contains(selectedQuery))
                    {
                        cmbQueryList.SelectedItem = selectedQuery;
                    }
                    else
                    {
                        cmbQueryList.SelectedIndex = 0;
                    }
                }
                else
                {
                    tbxTFSServerInfo.Text = "Click 'Connect...'";
                }
            }
            else
            {
                tbxTFSServerInfo.Text = "Click 'Connect...'";
            }
        }

        private void RefreshQuery()
        {
            try
            {
                var selectedItem = cmbQueryList.SelectedItem;

                if (selectedItem is TFSStoredQueryDefinition)
                {
                    var queryDef = (TFSStoredQueryDefinition)selectedItem;
                    var query = this.connection.WorkItemStore.Query(queryDef);
                    dgWorkItems.ItemsSource = query;

                    var settings = Properties.Settings.Default;
                    settings.QueryName = queryDef.Path;
                    settings.Save();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured.  " + ex.Message);
            }
        }

        private void QueryListComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.RefreshQuery();
        }

        private void OpenTestCaseButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedItem = dgWorkItems.SelectedItem as TFSWorkItem;

            if (selectedItem != null)
            {
                var testCaseView = new TestCaseView();
                testCaseView.ViewDataContext = new TestCaseDataContext(this.connection.TestManagement.TestTeamProject.GetTestCase(selectedItem.Id), this.connection.TestManagement.TestTeamProject);
                testCaseView.ShowDialog();
            }
        }

        private void WorkItemsGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedItem = dgWorkItems.SelectedItem as TFSWorkItem;

            if (selectedItem != null)
            {
                this.btnOpenTestCase.IsEnabled = selectedItem.WorkItemType.Name == "Test Case";
            }
        }

        private void Window_Activated(object sender, EventArgs e)
        {
            if (this.isFirstTimeActivated)
            {
                return;
            }

            this.isFirstTimeActivated = true;

            this.LoadServerFromSettings();
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            this.LoadServerFromSettings();
        }
    }
}
